package com.huaboot.system.strategy.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.huaboot.commont.exception.BusinessException;
import com.huaboot.system.entity.SysObjectStoreEntity;
import com.huaboot.system.enums.UploadModeEnum;
import com.huaboot.system.service.SysObjectStoreService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * description: 阿里oss上传策略实现
 * author: ff
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OssUploadStrategyImpl extends AbstractUploadStrategyImpl {

    private final SysObjectStoreService objectStoreService;
    private OSS ossClient;

    private SysObjectStoreEntity objectStore;

    @Override
    public void initClient() {
        objectStore = objectStoreService.getObjectStoreByLabel(UploadModeEnum.OSS_UPLOAD.getMode());
        ossClient = new OSSClientBuilder().build(objectStore.getEndpoint(), objectStore.getAccessKey(), objectStore.getAccessKeySecret());
        log.info("OssClient Init Success...");
    }

    @Override
    public boolean checkFileIsExisted(String fileRelativePath, String fileName) {
        boolean isExisted;
        try {
            isExisted = ossClient.doesObjectExist(objectStore.getBucket(), fileRelativePath + fileName);
        }catch (Exception e){
            throw new BusinessException("对象存储服务连接失败，请检查配置后重新测试！");
        }
        return isExisted;
    }

    @Override
    public void executeUpload(MultipartFile file, String fileRelativePath, String fileName) throws IOException {
        log.info("File Upload Starts...");
        try {
            ossClient.putObject(objectStore.getBucket(), fileRelativePath + fileName, file.getInputStream());
        }catch (Exception e){
            throw new BusinessException("存储桶不存在，请检查配置后重新测试！");
        }
        log.info("File Upload Finish...");
    }

    @Override
    public String getPublicNetworkAccessUrl(String fileRelativePath, String fileName) {
        return objectStore.getDomainUrl() + fileRelativePath + fileName;
    }


}
